package com.xcf.cloud.codesvc.service.impl;

import com.xcf.cloud.codesvc.dao.AuthCodeRepository;
import com.xcf.cloud.codesvc.entity.AuthCode;
import com.xcf.cloud.codesvc.service.ICodeService;
import com.xcf.cloud.mailsvc.client.EmailClient;
import com.xcf.cloud.userapi.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private EmailClient emailClient;
    @Autowired
    private AuthCodeRepository authCodeRepository;

    private char[] code = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    private char[] number_code = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    private String generateCode(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(number_code[random.nextInt(number_code.length)]);
        }
        return builder.toString();
    }

    @Override
    public boolean makeAndSendCode(String email) {
        boolean isRegister = userClient.checkRegister(email);
        if (isRegister) {
            return false;
        }
        AuthCode authCode = authCodeRepository.findTopByEmailOrderByIdDesc(email);
        long now = System.currentTimeMillis();
        if (null != authCode) {
            if ((now - authCode.getCreateTime().getTime()) <= 60 * 1000) {
                return false;
            }
        }
        AuthCode code = new AuthCode();
        code.setEmail(email);
        code.setCode(generateCode(6));
        code.setCreateTime(new Date(now));
        code.setExpireTime(new Date(now + 10 * 60 * 1000));
        authCodeRepository.save(code);
        try {
            emailClient.sendMail(email, code.getCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public Integer validCode(String email, String code) {
        AuthCode authCode = authCodeRepository.findTopByEmailAndCodeOrderByIdDesc(email, code);
        if (null == authCode) {
            return 1;
        }
        if (authCode.getExpireTime().before(new Date())) {
            return 2;
        }
        return 0;
    }
}
